package cn.edu.fzu.delivery.service.customer.impl;

import cn.edu.fzu.delivery.domain.entity.Address;
import cn.edu.fzu.delivery.domain.entity.Area;
import cn.edu.fzu.delivery.domain.entity.Network;
import cn.edu.fzu.delivery.exception.ServiceException;
import cn.edu.fzu.delivery.mapper.AddressMapper;
import cn.edu.fzu.delivery.mapper.AreaMapper;
import cn.edu.fzu.delivery.service.NetworkService;
import cn.edu.fzu.delivery.service.customer.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper  addressMapper;
    @Resource
    private NetworkService networkService;

    @Override
    public List<Address> list(Long customerId) {
        return addressMapper.list(customerId);
    }


    @Override
    public Address getById(Long id) {
        return addressMapper.getById(id);
    }


    @Override
    public void add(Long customerId, String name, String phone, String email, Long networkId, String address) {
        Network network = networkService.getById(networkId);
        if (network == null) {
            throw new ServiceException("未找到对应网点");
        }
        List<Address> list = addressMapper.list(customerId);
        if (!CollectionUtils.isEmpty(list)) {
            for (Address a : list) {
                if (Objects.equals(a.getNetwork().getId(), networkId) && Objects.equals(a.getName(), name)) {
                    throw new ServiceException("已经存在该网点和该名字的组合");
                }
            }
        }
        addressMapper.insert(customerId, name, phone, email, networkId, address);
    }


    @Override
    public void update(Long customerId, Long addressId, String name, String phone, String email, Long networkId,
                       String address) {
        Address add = addressMapper.getById(addressId);
        if (!Objects.equals(add.getCustomerId(), customerId)) {
            throw new ServiceException("地址不存在");
        }
        Network network = networkService.getById(networkId);
        if (network == null) {
            throw new ServiceException("未找到对应网点");
        }
        addressMapper.update(addressId, name, phone, email, networkId, address);
    }


    @Override
    public void delete(Long customerId, Long id) {
        Address address = addressMapper.getById(id);
        if (Objects.equals(address.getCustomerId(), customerId)) {
            addressMapper.delete(id);
        } else {
            throw new ServiceException("非法操作");
        }
    }
}
